<?php
class ControllerNewsletterTemplate extends Controller {
    private $error = array(); 
    
    public function index() {
        $this->load->model('newsletter/template');        
        $this->load->language('newsletter/template');        
        $this->document->title = $this->language->get('heading_title');
        
        $this->getList();   
    }
    
	public function simple() {
        $this->load->model('newsletter/template');        
        $this->load->language('newsletter/template');        
        $this->document->title = $this->language->get('heading_title');
        
        $this->getList(1);   
    }
	
    public function insert() {
    	$this->load->model('newsletter/template');        
        $this->load->language('newsletter/template');   
    	$this->document->title = $this->language->get('heading_title'); 
		
    	if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {			
			$this->model_newsletter_template->addTemplate($this->request->post);
	  		
			$this->session->data['success'] = $this->language->get('text_success');
	  
			$url = $this->getFilter(); 
			$this->redirect(HTTPS_SERVER . 'index.php?route=newsletter/template' . $url . '&token=' . $this->session->data['token']);
    	}
	
    	$this->getForm();
  	}
    
	public function insertSimple() {
    	$this->load->model('newsletter/template');        
        $this->load->language('newsletter/template');   
    	$this->document->title = $this->language->get('heading_title'); 
		
    	if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate(1)) {			
			$this->model_newsletter_template->addTemplate($this->request->post);
	  		
			$this->session->data['success'] = $this->language->get('text_success');
	  
			$url = $this->getFilter(); 
			$this->redirect(HTTPS_SERVER . 'index.php?route=newsletter/template/simple' . $url . '&token=' . $this->session->data['token']);
    	}
	
    	$this->getForm(1);
  	}
	
    public function update() {
    	$this->load->model('newsletter/template');        
        $this->load->language('newsletter/template');   
    	$this->document->title = $this->language->get('heading_title'); 
			
    	if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {			
			$this->model_newsletter_template->updateTemplate($this->request->get['template_id'], $this->request->post);
			
			$this->session->data['success'] = $this->language->get('text_success');
			
			$url = $this->getFilter();			
			$this->redirect(HTTPS_SERVER . 'index.php?route=newsletter/template' . $url . '&token=' . $this->session->data['token']);
		}

    	$this->getForm();
  	}
    
	public function updateSimple() {
    	$this->load->model('newsletter/template');        
        $this->load->language('newsletter/template');   
    	$this->document->title = $this->language->get('heading_title'); 
			
    	if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate(1)) {			
			$this->model_newsletter_template->updateTemplate($this->request->get['template_id'], $this->request->post);
			
			$this->session->data['success'] = $this->language->get('text_success');
			
			$url = $this->getFilter();			
			$this->redirect(HTTPS_SERVER . 'index.php?route=newsletter/template/simple' . $url . '&token=' . $this->session->data['token']);
		}

    	$this->getForm(1);
  	}
	
    public function delete() {
    	$this->load->model('newsletter/template');        
        $this->load->language('newsletter/template');   
    	$this->document->title = $this->language->get('heading_title');
		
		if (isset($this->request->post['selected']) && $this->validateDelete()) {
			foreach ($this->request->post['selected'] as $template_id) {
				$this->model_newsletter_template->deleteTemplate($template_id);
	  		}

			$this->session->data['success'] = $this->language->get('text_delete_success');
			
			$url = $this->getFilter();
			$this->redirect(HTTPS_SERVER . 'index.php?route=newsletter/template' . $url . '&token=' . $this->session->data['token']);
		}

    	$this->getList();
  	}

	public function deleteSimple() {
    	$this->load->model('newsletter/template');        
        $this->load->language('newsletter/template');   
    	$this->document->title = $this->language->get('heading_title');
		
		if (isset($this->request->post['selected']) && $this->validateDelete()) {
			foreach ($this->request->post['selected'] as $template_id) {
				$this->model_newsletter_template->deleteTemplate($template_id);
	  		}

			$this->session->data['success'] = $this->language->get('text_delete_success');
			
			$url = $this->getFilter();
			$this->redirect(HTTPS_SERVER . 'index.php?route=newsletter/template/simple' . $url . '&token=' . $this->session->data['token']);
		}

    	$this->getList(1);
  	}
	
    public function getList($simple = 0){        
        if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];            
		} else {
			$page = 1;
		}
		
		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];            
		} else {
			$sort = 'title';
		}
		
		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'ASC';
		}
        
        if (isset($this->request->get['filter_code'])) {
			$filter_code = $this->request->get['filter_code'];
		} else {
			$filter_code = NULL;
		}
        
        if (isset($this->request->get['filter_title'])) {
			$filter_title = $this->request->get['filter_title'];
		} else {
			$filter_title = NULL;
		}
        
		if (isset($this->request->get['filter_status'])) {
			$filter_status = $this->request->get['filter_status'];
		} else {
			$filter_status = NULL;
		}
        
        $url = $this->getFilter();
        
  		$this->document->breadcrumbs = array();
   		$this->document->breadcrumbs[] = array(
       		'href'      => HTTPS_SERVER . 'index.php?route=common/home&token=' . $this->session->data['token'],
       		'text'      => $this->language->get('text_home'),
      		'separator' => FALSE
   		);
   		$this->document->breadcrumbs[] = array(
       		'href'      => HTTPS_SERVER . 'index.php?route=newsletter/template&token=' . $this->session->data['token'] . $url,
       		'text'      => $this->language->get('heading_title'),
      		'separator' => ' :: '
   		);
		
		if($simple){
			$this->data['insert'] = HTTPS_SERVER . 'index.php?route=newsletter/template/insertSimple' . $url . '&token=' . $this->session->data['token'];			
			$this->data['delete'] = HTTPS_SERVER . 'index.php?route=newsletter/template/deleteSimple' . $url . '&token=' . $this->session->data['token'];
		}
		else{
			$this->data['insert'] = HTTPS_SERVER . 'index.php?route=newsletter/template/insert' . $url . '&token=' . $this->session->data['token'];
			$this->data['copy'] = HTTPS_SERVER . 'index.php?route=newsletter/template/copy' . $url . '&token=' . $this->session->data['token'];	
			$this->data['delete'] = HTTPS_SERVER . 'index.php?route=newsletter/template/delete' . $url . '&token=' . $this->session->data['token'];
		}
    	    
        $data = array(
			'filter_code'	  => $filter_code,
            'filter_title'    => $filter_title,
            'filter_status'   => $filter_status,
			'sort'            => $sort,
			'order'           => $order,
			'start'           => ($page - 1) * $this->config->get('config_admin_limit'),
			'limit'           => $this->config->get('config_admin_limit')
		);
        
		$template_total = $this->model_newsletter_template->getTotalTemplates($data, $simple);			
		$results = $this->model_newsletter_template->getTemplates($data, $simple);	
        	
        $this->data['templates'] = array();		    	
		foreach ($results as $result) {
			if($simple){
				$edit_template_link = HTTPS_SERVER . 'index.php?route=newsletter/template/updateSimple&template_id=' . $result['template_id'] . $url . '&token=' . $this->session->data['token'];
			}
			else{
				$edit_template_link = HTTPS_SERVER . 'index.php?route=newsletter/template/update&template_id=' . $result['template_id'] . $url . '&token=' . $this->session->data['token'];
			}
			$action = array();
			$action[] = array(
				'text' => $this->language->get('text_edit'),
				'href' => $edit_template_link,
			);
			
      		$this->data['templates'][] = array(
				'template_id'   => $result['template_id'],
                'code'          => $result['code'],
				'title'         => html_entity_decode($result['title']),
                'status'        => $result['status'],
                'description'   => $result['description'],				
				'action'        => $action,
                'selected'      => isset($this->request->post['selected']) && in_array($result['template_id'], $this->request->post['selected']),
			);
    	}
		
		$this->data['heading_title'] = $this->language->get('heading_title');
        $this->data['text_list_template'] = $this->language->get('text_list_template');

		$this->data['text_enabled'] = $this->language->get('text_enabled');
		$this->data['text_disabled'] = $this->language->get('text_disabled');
		$this->data['text_no_results'] = $this->language->get('text_no_results');
		$this->data['text_image_manager'] = $this->language->get('text_image_manager');
        
        $this->data['column_code'] = $this->language->get('column_code');
        $this->data['column_title'] = $this->language->get('column_title');
		$this->data['column_status'] = $this->language->get('column_status');
		$this->data['column_action'] = $this->language->get('column_action');
		
		$this->data['button_copy'] = $this->language->get('button_copy');
		$this->data['button_insert'] = $this->language->get('button_insert');
		$this->data['button_delete'] = $this->language->get('button_delete');
		$this->data['button_filter'] = $this->language->get('button_filter');
 
 		$this->data['token'] = $this->session->data['token'];
		
 		if (isset($this->error['warning'])) {
			$this->data['error_warning'] = $this->error['warning'];
		} else {
			$this->data['error_warning'] = '';
		}

		if (isset($this->session->data['success'])) {
			$this->data['success'] = $this->session->data['success'];
		
			unset($this->session->data['success']);
		} else {
			$this->data['success'] = '';
		}

		$url = '';
        if (isset($this->request->get['filter_code'])) {
            $url .= '&filter_code=' . $filter_code;
        } 
        if (isset($this->request->get['filter_title'])) {
            $url .= '&filter_title=' . $filter_title;
        }        
        if (isset($this->request->get['filter_status'])) {
            $url .= '&filter_status=' . $filter_status;
        }         
        if ($order == 'ASC') {
			$url .= '&order=DESC';
		}
        else {
			$url .= '&order=ASC';
		}
        
		$this->data['sort_code'] = HTTPS_SERVER . 'index.php?route=newsletter/template&sort=code' . $url . '&token=' . $this->session->data['token'];		
        $this->data['sort_title'] = HTTPS_SERVER . 'index.php?route=newsletter/template&sort=title' . $url . '&token=' . $this->session->data['token'];		
		$this->data['sort_status'] = HTTPS_SERVER . 'index.php?route=newsletter/template&sort=status' . $url . '&token=' . $this->session->data['token'];
        
        if (isset($this->request->get['sort'])) {			
            $url .= '&sort=' . $sort;
        }
		$pagination = new Pagination();
		$pagination->total = $template_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_admin_limit');
		$pagination->text = $this->language->get('text_pagination');
		$pagination->url = HTTPS_SERVER . 'index.php?route=newsletter/template' . $url . '&page={page}&token=' . $this->session->data['token'];
			
		$this->data['pagination'] = $pagination->render();
		        
        $this->data['filter_code'] = $filter_code;
        $this->data['filter_title'] = $filter_title;        
		$this->data['filter_status'] = $filter_status;
        
		$this->data['sort'] = $sort;
		$this->data['order'] = $order;
                
        
		$this->template = 'newsletter/template_list.tpl';
		$this->children = array(
			'common/header',	
			'common/footer'	
		);
		
		$this->response->setOutput($this->render(TRUE), $this->config->get('config_compression'));
    }
    
    public function getForm($simple = 0) {           
        $this->document->title = $this->language->get('heading_title');       
          
        if (isset($this->request->get['template_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
      		$template_info = $this->model_newsletter_template->getTemplate($this->request->get['template_id']);
    	}
        
        $this->data['heading_title'] = $this->language->get('heading_title');
        $this->data['text_enabled'] = $this->language->get('text_enabled');
        $this->data['text_disabled'] = $this->language->get('text_disabled');        
        $this->data['text_image_manager'] = $this->language->get('Image Manager');   
        
        $this->data['entry_code'] = $this->language->get('entry_code');
        $this->data['entry_title'] = $this->language->get('entry_title');
        $this->data['entry_description'] = $this->language->get('entry_description');
        $this->data['entry_product_title'] = $this->language->get('entry_product_title');
		$this->data['entry_footer_text'] = $this->language->get('entry_footer_text');
        $this->data['entry_limit'] = $this->language->get('entry_limit');
        $this->data['entry_status'] = $this->language->get('entry_status');
        $this->data['entry_product'] = $this->language->get('entry_product');
        $this->data['entry_product_area'] = $this->language->get('entry_product_area');
        
        $this->data['button_save'] = $this->language->get('button_save');
        $this->data['button_cancel'] = $this->language->get('button_cancel');

         if (isset($this->error['warning'])) {
            $this->data['error_warning'] = $this->error['warning'];
        } else {
            $this->data['error_warning'] = '';
        }

        $url = $this->getFilter();
        
        $this->document->breadcrumbs = array();
        $this->document->breadcrumbs[] = array(
            'href'      => HTTPS_SERVER . 'index.php?route=common/home&token=' . $this->session->data['token'],
            'text'      => $this->language->get('text_home'),
           'separator' => FALSE
        );
		
		if($simple){
			$template_link = HTTPS_SERVER . 'index.php?route=newsletter/template/simple' . $url . '&token=' . $this->session->data['token'];
			$update_link = HTTPS_SERVER . 'index.php?route=newsletter/template/updateSimple' . $url . '&token=' . $this->session->data['token'];
			$insert_item = HTTPS_SERVER . 'index.php?route=newsletter/template/insertSimple' . $url . '&token=' . $this->session->data['token'];
			$update_item = HTTPS_SERVER . 'index.php?route=newsletter/template/updateSimple&template_id=%s' . $url . '&token=' . $this->session->data['token'];
			$cancel_link = HTTPS_SERVER . 'index.php?route=newsletter/template/simple' . $url . '&token=' . $this->session->data['token'];
		}
		else{
			$template_link = HTTPS_SERVER . 'index.php?route=newsletter/template' . $url . '&token=' . $this->session->data['token'];
			$update_link = HTTPS_SERVER . 'index.php?route=newsletter/template/update' . $url . '&token=' . $this->session->data['token'];
			$insert_item = HTTPS_SERVER . 'index.php?route=newsletter/template/insert' . $url . '&token=' . $this->session->data['token'];
			$update_item = HTTPS_SERVER . 'index.php?route=newsletter/template/update&template_id=%s' . $url . '&token=' . $this->session->data['token'];
			$cancel_link = HTTPS_SERVER . 'index.php?route=newsletter/template' . $url . '&token=' . $this->session->data['token'];
		}
	
        $this->document->breadcrumbs[] = array(
            'href'      => $template_link,
            'text'      => $this->language->get('heading_title'),
           'separator' => ' :: '
        );        
        $this->document->breadcrumbs[] = array(
            'href'      => $update_link,
            'text'      => $this->language->get('heading_title'),
           'separator' => ' :: '
        );
        
        if (!isset($this->request->get['template_id'])) {			
            $this->data['action'] = $insert_item;
		} else {
			$this->data['action'] = sprintf($update_item, $this->request->get['template_id']);
		}
        
        $this->data['cancel'] = $cancel_link;
        $this->data['token'] = $this->session->data['token'];
        
        if (isset($this->request->post['code'])) {
            $this->data['code'] = $this->request->post['code'];
        }
        elseif(isset($template_info)){
            $this->data['code'] = $template_info['code'];
        }
        else {
            $this->data['code'] = ''; 
        }  
               
        if (isset($this->request->post['title'])) {
            $this->data['title'] = $this->request->post['title'];
        }
        elseif(isset($template_info)){
            $this->data['title'] = $template_info['title'];
        }
        else {
            $this->data['title'] = '';
        }
        
        if (isset($this->request->post['description'])) {
            $this->data['description'] = $this->request->post['description'];
        }
        elseif(isset($template_info)){
            $this->data['description'] = $template_info['description'];
        }
        else {
            $this->data['description'] = '';
        }
        
        if (isset($this->request->post['product_title'])) {
            $this->data['product_title'] = $this->request->post['product_title'];
        }
        elseif(isset($template_info)){
            $this->data['product_title'] = $template_info['product_title'];
        }
        else {
            $this->data['product_title'] = '';
        }                
        
		if (isset($this->request->post['footer_text'])) {
            $this->data['footer_text'] = $this->request->post['footer_text'];
        }
        elseif(isset($template_info)){
            $this->data['footer_text'] = $template_info['footer_text'];
        }
        else {
            $this->data['footer_text'] = '';
        }
		
        if (isset($this->request->post['status'])) {
            $this->data['status'] = $this->request->post['status'];
        }
        elseif(isset($template_info)){
            $this->data['status'] = $template_info['status'];
        }
        else {
            $this->data['status'] = '1';
        }
        
        if (isset($this->request->post['product_limit'])) {
            $this->data['product_limit'] = $this->request->post['product_limit'];
        }
        elseif(isset($template_info)){
            $this->data['product_limit'] = 8; //$template_info['product_limit'];
        }
        else {
            $this->data['product_limit'] = 8;
        }
          
		if (isset($this->request->post['template_layout'])) {
            $this->data['template_layout'] = $this->request->post['template_layout'];
        }
        elseif(isset($template_info)){
            $this->data['template_layout'] = $template_info['layout'];
        }
        else {
            $this->data['template_layout'] = 'default';
        }
		
        $this->load->model('catalog/category');                
        $this->data['categories'] = $this->model_catalog_category->getEnableCategories(0);
        
        if (isset($this->request->post['product_featured'])) {
            $this->data['product_featured'] = $this->request->post['product_featured'];
        }
        elseif(isset($template_info)){
            $this->data['product_featured'] = $this->model_newsletter_template->getProducts($this->request->get['template_id']);
        }
        else {
              $this->data['product_featured'] = array();
        }
        
        $this->load->model('tool/image'); 
        foreach($this->data['product_featured'] as &$featured){
            if($featured['image'] && file_exists(DIR_IMAGE . $featured['image'])) {
                $image_file = $featured['image'];    
            } 
            else {
                $image_file = 'no_image.jpg';
            }
            
            $featured['preview'] = $this->model_tool_image->resize($image_file, 100, 100);
                
        }
        
        if (isset($this->error['warning'])) {
			$this->data['error_warning'] = $this->error['warning'];
		} else {
			$this->data['error_warning'] = '';
		}

        if (isset($this->error['code'])) {
			$this->data['error_code'] = $this->error['code'];
		} else {
			$this->data['error_code'] = '';
		}
        
 		if (isset($this->error['title'])) {
			$this->data['error_title'] = $this->error['title'];
		} else {
			$this->data['error_title'] = '';
		}
        
        if (isset($this->error['description'])) {
			$this->data['error_description'] = $this->error['description'];
		} else {
			$this->data['error_description'] = '';
		}
        
		if (isset($this->error['footer_text'])) {
			$this->data['error_footer_text'] = $this->error['footer_text'];
		} else {
			$this->data['error_footer_text'] = '';
		}
		
        if (isset($this->error['product_title'])) {
			$this->data['error_product_title'] = $this->error['product_title'];
		} else {
			$this->data['error_product_title'] = '';
		}
        if (isset($this->error['products'])) {
			$this->data['error_products'] = $this->error['products'];
		} else {
			$this->data['error_products'] = '';
		}
        
		if($simple){
			$this->template = 'newsletter/template_form_simple.tpl';
		}
		else{
			$this->template = 'newsletter/template_form.tpl';
		}
        $this->children = array(
            'common/header',    
            'common/footer'    
        );
        
        $this->response->setOutput($this->render(TRUE), $this->config->get('config_compression'));
    }
    
    private function validate($simple = 0) { 
    	if (!$this->user->hasPermission('modify', 'newsletter/template')) {
      		$this->error['warning'] = $this->language->get('error_permission');
    	}

        if ((strlen(utf8_decode($this->request->post['code'])) < 1) || (strlen(utf8_decode($this->request->post['code'])) > 255)) {
            $this->error['code'] = $this->language->get('error_code');
        }
        
        if ((strlen(utf8_decode($this->request->post['title'])) < 1) || (strlen(utf8_decode($this->request->post['title'])) > 255)) {
            $this->error['title'] = $this->language->get('error_title');
        }
    	
        if (strlen(utf8_decode($this->request->post['description'])) < 1) {
            $this->error['description'] = $this->language->get('error_description');
        }
        
		if(!$simple){
			if ((strlen(utf8_decode($this->request->post['product_title'])) < 1) || (strlen(utf8_decode($this->request->post['product_title'])) > 255)) {
				$this->error['product_title'] = $this->language->get('error_product_title');
			}
			
			if (strlen(utf8_decode($this->request->post['footer_text'])) < 1){
				$this->error['footer_text'] = $this->language->get('footer_text');
			}
			
			if (!isset($this->request->post['product_featured']) || empty($this->request->post['product_featured'])) {
				$this->error['products'] = $this->language->get('error_products');
			}
		}
		
    	if (!$this->error) {
			return TRUE;
    	}
        else {
			if (!isset($this->error['warning'])) {
				$this->error['warning'] = $this->language->get('error_required_data');
			}
      		return FALSE;
    	}
  	}
	
  	private function validateDelete() {
    	if (!$this->user->hasPermission('modify', 'newsletter/template')) {
      		$this->error['warning'] = $this->language->get('error_permission');  
    	}
		
		if (!$this->error) {
	  		return TRUE;
		} else {
	  		return FALSE;
		}
  	}
    
    public function category() {
        $this->load->model('catalog/product');
        
        if (isset($this->request->get['category_id'])) {
            $category_id = $this->request->get['category_id'];
        } else {
            $category_id = 0;
        }
        
        $product_data = array();
        
        $results = $this->model_catalog_product->getProductsByCategoryId($category_id);
        $this->load->model('tool/image');
        
        foreach ($results as $result) {
            if($result['image'] && file_exists(DIR_IMAGE . $result['image'])) {
                $image_file = $result['image'];    
            } 
            else {
                $image_file = 'no_image.jpg';
            }
            
            $product_data[] = array(
                'product_id' => $result['product_id'],
                'name'       => $result['name'],
                'model'      => $result['model'],
                'sku'        => $result['sku'],
                'price'      => $result['price'],
                'image'      => $result['image'],
                'preview'    => $this->model_tool_image->resize($image_file, 100, 100),                
            );
        }
        
        $this->load->library('json');
        
        $this->response->setOutput(Json::encode($product_data));
    }
    
    public function product() {
        $this->load->model('catalog/product');
        
        if (isset($this->request->post['product_featured'])) {
            $products = $this->request->post['product_featured'];
        } else {
            $products = array();
        }
    
        $product_data = array();
        
        foreach ($products as $product_id) {
            $product_info = $this->model_catalog_product->getProduct($product_id);   
                         
            if ($product_info) {
                $product_data[] = array(
                    'product_id' => $product_info['product_id'],
                    'name'       => $product_info['name'],
                    'model'      => $product_info['model'],
                    'sku'        => $product_info['sku'],
                    'price'      => $result['price'],
                    'image'      => $result['image'],
                );
            }
        }
        
        $this->load->library('json');
        
        $this->response->setOutput(Json::encode($product_data));
    }
    
    private function getFilter(){
        $url = '';
        
        if (isset($this->request->get['filter_title'])) {
            $url .= '&filter_title=' . $this->request->get['filter_title'];
        }
        
        if (isset($this->request->get['filter_status'])) {
            $url .= '&filter_status=' . $this->request->get['filter_status'];
        }
                
        if (isset($this->request->get['page'])) {
            $url .= '&page=' . $this->request->get['page'];
        }

        if (isset($this->request->get['sort'])) {
            $url .= '&sort=' . $this->request->get['sort'];
        }
        
        if (isset($this->request->get['order'])) {			
            $url .= '&order=' . $this->request->get['order'];
        }
        
        return $url;
    }
}
?>